<?php
$con = mysql_connect("localhost","root","");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
 
mysql_select_db("player_profile", $con);

$award_title = "Bednarik Award";
$fn = "bednarik.csv";
$handle = @fopen($fn, "r");
if ($handle) {
	echo "Bednarik Winners:<br>";
    while (($buffer = fgets($handle, 4096)) !== false) {
        $line = explode(',', $buffer);
		$year = trim($line[0]);
		echo "$year: ";
		for($i = 1; $i < sizeof($line); $i++){
			$name = trim($line[1]);
			$names = explode(' ', $name);
			if(sizeof($names) > 2){
				$first = join(" ", array_slice($names, 0, sizeof($names) - 1));
				$last = $names[sizeof($names) - 1];
			}
			else{
				$first = $names[0];
				$last = $names[1];
			}
			$first = str_replace("\"", "", $first);
			$last = str_replace("\"", "", $last);
			$college = str_replace("\"", "", trim($line[2]));
			echo "First: /$first/, Last: /$last/, College: /$college/<br>";
			$player_select = " 	SELECT id FROM players
								WHERE first_name='$first' and last_name='$last' and college='$college'";
			$result = mysql_query($player_select);
			$r = mysql_fetch_assoc($result);
			echo "R: ".var_dump($r)."<br>";
			$id = $r['id'];
			if(!$r){
				$player_insert = "	INSERT into players (first_name, last_name, college)
									VALUES ('$first', '$last', '$college')";
				echo "Player insert: $player_insert <br>";
				mysql_query($player_insert);
				$result = mysql_query($player_select);
				$r = mysql_fetch_assoc($result);
				echo "R: ".var_dump($r)."<br>";
				$id = $r['id'];				
			}			
			echo "<br>Player: $id, $first, $last, $college<br> Award: ";
			$query = "	INSERT into awards (award_title, player_id, year) 
						VALUES ('$award_title', $id, $year)";
			echo "Award insert: $query<br><br>";
			$result = mysql_query($query);
		}
		echo "<br>";
    }
    if (!feof($handle)) {
        echo "Error: unexpected fgets() fail\n";
    }
    fclose($handle);
}
else
	echo "failed ro read file";

?>